﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Reactive;
using System.Reactive.Linq;
using System.Drawing;
using System.IO;


namespace YLServerInterface.UserControls
{
    /// <summary>
    /// Interaction logic for ImageCutter.xaml
    /// </summary>
    public partial class ImageCutter : UserControl
    {

        public ImageCutter()
        {
            InitializeComponent();
        }
        public string ImgPath { get; set; }
        public string SaveImgPath { get; set; }
        public double RectWidth { get; set; }
        public double RectHeight { get; set; }
        public bool CanCut { get; private set; }
        private BitmapImage bitmapImg;
        private void updateRect(SizeChangedEventArgs e)
        {
            if (bitmapImg == null)
                return;
            #region 图片大小检查
            if (bitmapImg.PixelWidth < RectWidth || bitmapImg.PixelHeight < RectHeight)
            {
                CanCut = false;
                labError.Visibility = System.Windows.Visibility.Visible;
                return;
            }
            else
                CanCut = true;
            #endregion
            #region 改变rect的位置，按比例改变
            if (e.PreviousSize.Width != 0 && e.PreviousSize.Height != 0)
            {
                var _x = e.NewSize.Width / e.PreviousSize.Width;
                var _y = e.NewSize.Height / e.PreviousSize.Height;
                rect.Margin = new Thickness(rect.Margin.Left * _x, rect.Margin.Top * _y, rect.Margin.Right, rect.Margin.Bottom);
            }

            #endregion
            #region 改变rect 的大小
            var imgWidth = bitmapImg.PixelWidth;
            //var imgHeight = bitmapImg.Height;
            var imgControlWidth = img.ActualWidth;
            // var imgControlHeight = img.ActualHeight;
            //计算缩放比例
            double scale = imgControlWidth / imgWidth;
            rect.Width = scale * RectWidth;
            rect.Height = scale * RectHeight;

            #endregion
        }
        private bool isRectOutImg(double dx, double dy)
        {
            var right = rect.Margin.Left + rect.Width + dx;
            var bottom = rect.Margin.Top + rect.Height + dy;
            var a = right > this.ActualWidth || bottom > this.ActualHeight ? true : false;
            var left = rect.Margin.Left + dx;
            var top = rect.Margin.Top + dy;
            var b = left < 0 || top < 0 ? true : false;
            return a || b;
        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //bitmapImg = new BitmapImage(new Uri(ImgPath));
            //ImageSource imgSrc = bitmapImg;
            //img.Source = imgSrc;
        }

        private void img_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            updateRect(e);
        }


        private void rect_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var pre = e.GetPosition(this as IInputElement);

            var mMove = Observable.FromEventPattern<MouseEventArgs>(this, "MouseMove");
            var mUp = Observable.FromEventPattern<MouseEventArgs>(this, "MouseUp");
            var move = mMove.TakeUntil(mUp);

            var mMoveDiff = move.Select(curr =>
            {
                var currPos = curr.EventArgs.GetPosition(curr.Sender as IInputElement);
                var ret = new { PrePos = pre, CurrPos = currPos };
                pre = currPos;
                return ret;
            });
            mMoveDiff.Subscribe(poses =>
            {
                //  Console.Write("{0},{1} ->", poses.PrePos.X, poses.PrePos.Y);
                //   Console.WriteLine("{0},{1}", poses.CurrPos.X, poses.CurrPos.Y);
                var dX = poses.CurrPos.X - poses.PrePos.X;
                var dY = poses.CurrPos.Y - poses.PrePos.Y;
                //Console.WriteLine("{0},{1}", dX, dY);
                if (!isRectOutImg(dX, dY))
                {
                    //  Console.WriteLine("{0},{1}", dX, dY);
                    rect.Margin = new Thickness(
                        rect.Margin.Left + dX,
                        rect.Margin.Top + dY,
                        rect.Margin.Right,
                        rect.Margin.Bottom);
                }
            });

        }
        /// <summary>
        /// 执行剪切图片，并且根据传入名字进行保存
        /// </summary>
        /// <param name="outputImgName"></param>
        public void Cut()
        {
            if (CanCut == false)
            {
                return;
            }
            if (SaveImgPath == "")
            {
                return;
            }
            if (!File.Exists(SaveImgPath))
            {
                File.Create(SaveImgPath);
            }

            using (Bitmap bitmap = new Bitmap(ImgPath))
            {
                var scale = bitmap.Width / this.img.ActualWidth;
                //框框控件的信息
                PointF rectPf = new PointF((float)rect.Margin.Left, (float)rect.Margin.Top);
                //根据框框信息，计算出实际在图片中截取的左上角坐标
                var imgPx = (float)(scale * rectPf.X);
                var imgPy = (float)(scale * rectPf.Y);
                //剪裁图片左上角坐标
                PointF imgPf = new PointF(imgPx, imgPy);
                //剪裁图片大小
                var imgSizef = new SizeF((float)RectWidth, (float)RectHeight);
                RectangleF rectf = new RectangleF(imgPf, imgSizef);
                //复制图片指定位置
                using (var newBitmap = bitmap.Clone(rectf, System.Drawing.Imaging.PixelFormat.Format1bppIndexed))
                {
                    newBitmap.Save(SaveImgPath);
                    //不需要使用gdi+ 直接在图片中clone即可
                    //using (Bitmap newImg = new Bitmap((int)rectf.Width, (int)rectf.Height))
                    //{
                    //    using (Graphics graphics = Graphics.FromImage(newImg))
                    //    {
                    //        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                    //        graphics.DrawImage(newBitmap, new RectangleF(0, 0, newBitmap.Width, newBitmap.Height));
                    //        newImg.Save(SaveImgPath);
                    //    }
                    //}
                }
            }
        }
    }
}
